using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
//
// DotNetNuke?- http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//
using System.IO;
using DotNetNuke;
using System.Web.UI;
using System.Reflection;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI;
using DotNetNuke.UI.Skins.Controls;
using System.Linq;
using System.Xml;
using DotNetNuke.Application;

namespace DotNetNuke.Modules.XmlMerge
{

    partial class XmlMerge : Entities.Modules.PortalModuleBase
    {

        #region "Private Functions"

        private bool IsValidDocType(string contentType)
        {
            switch (contentType)
            {
                case "text/plain":
                case "application/xml":
                    return true;
                default:
                    return false;
            }
        }

        private bool IsValidXmlMergDocument(string mergeDocText)
        {
            if (string.IsNullOrEmpty(mergeDocText.Trim()))
            {
                return false;
            }
            //TODO: Add more checks here
            return true;
        }

        private void BindConfigList()
        {
            string[] files = System.IO.Directory.GetFiles(DotNetNuke.Common.Globals.ApplicationMapPath, "*.config");
            var fileList = (from file in files select Path.GetFileName(file));
            ddlConfig.DataSource = fileList;
            ddlConfig.DataBind();
            Telerik.Web.UI.RadComboBoxItem selectItem = new Telerik.Web.UI.RadComboBoxItem(Localization.GetString("SelectConfig", LocalResourceFile), "-1");
            ddlConfig.Items.Insert(0, selectItem);
            ddlConfig.SelectedIndex = 0;

        }

        private void ValidateSuperUser()
        {
            // Verify that the current user has access to access this page
            if (!UserInfo.IsSuperUser)
            {
                Response.Redirect(Globals.NavigateURL("Access Denied"), true);
            }
        }

        private void LoadConfig(string configFile)
        {
            System.Xml.XmlDocument configDoc = Config.Load(configFile);
            using (System.IO.StringWriter txtWriter = new System.IO.StringWriter())
            {
                using (XmlTextWriter writer = new XmlTextWriter(txtWriter))
                {
                    writer.Formatting = Formatting.Indented;
                    configDoc.WriteTo(writer);
                }
                txtConfiguration.Text = txtWriter.ToString();
            }
        }

        #endregion

        #region "Event Handlers"

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            cmdExecute.Click += new EventHandler(cmdExecute_Click);
            cmdSave.Click += new EventHandler(cmdSave_Click);
            cmdUpload.Click += new EventHandler(cmdUpload_Click);
            ddlConfig.SelectedIndexChanged += new Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventHandler(ddlConfig_SelectedIndexChanged);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            ValidateSuperUser();

            if (!Page.IsPostBack)
            {
                BindConfigList();
            }
            else
            {
                if (ddlConfig.SelectedIndex != 0)
                {
                    ddlConfig.Attributes.Add("onClick", "javascript: alert('" + Localization.GetString("LoadConfigWarning", LocalResourceFile) + "');");
                    txtConfiguration.Enabled = true;
                    cmdSave.Enabled = true;
                }
                else
                {
                    ddlConfig.Attributes.Remove("onClick");
                    txtConfiguration.Text = string.Empty;
                    txtConfiguration.Enabled = true;
                    cmdSave.Enabled = false;
                }

            }

            if (ddlConfig.SelectedValue.ToLowerInvariant() == "web.config")
            {
                DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(cmdSave, Localization.GetString("SaveWarning", LocalResourceFile));
                DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(cmdExecute, Localization.GetString("SaveWarning", LocalResourceFile));
            }
            else if (ddlConfig.SelectedIndex == 0)
            {
                cmdSave.Attributes.Remove("onClick");
                cmdExecute.Attributes.Remove("onClick");
            }
            else
            {
                DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(cmdSave, Localization.GetString("SaveConfirm", LocalResourceFile));
                DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(cmdExecute, Localization.GetString("MergeConfirm", LocalResourceFile));
            }


        }

        protected void cmdExecute_Click(object sender, System.EventArgs e)
        {
            ValidateSuperUser();
            if (IsValidXmlMergDocument(txtScript.Text))
            {
                try
                {
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.LoadXml(txtScript.Text);
                    DotNetNuke.Application.Application app = DotNetNukeContext.Current.Application;
                    DotNetNuke.Services.Installer.XmlMerge merge = new DotNetNuke.Services.Installer.XmlMerge(doc, Globals.FormatVersion(app.Version), app.Description);
                    merge.UpdateConfigs();
                    Skin.AddModuleMessage(this, Localization.GetString("Success", this.LocalResourceFile),
                                                ModuleMessage.ModuleMessageType.GreenSuccess);
                }
                catch (Exception ex)
                {
                    Skin.AddModuleMessage(this, Localization.GetString("ERROR_Merge", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    Exceptions.LogException(ex);
                }
            }
        }

        protected void cmdSave_Click(object sender, System.EventArgs e)
        {
            ValidateSuperUser();
            System.Xml.XmlDocument configDoc = new System.Xml.XmlDocument();
            try
            {
                configDoc.LoadXml(txtConfiguration.Text);
                Config.Save(configDoc, ddlConfig.SelectedValue);
                LoadConfig(ddlConfig.SelectedValue);

                Skin.AddModuleMessage(this, Localization.GetString("Success", this.LocalResourceFile),
                                      ModuleMessage.ModuleMessageType.GreenSuccess);
            }
            catch (Exception ex)
            {
                Skin.AddModuleMessage(this, string.Format(Localization.GetString("ERROR_ConfigurationFormat", LocalResourceFile), ex.Message), ModuleMessage.ModuleMessageType.RedError);
                return;
            }
        }

        protected void cmdUpload_Click(object sender, System.EventArgs e)
        {
            ValidateSuperUser();
            if (IsValidDocType(uplScript.PostedFile.ContentType))
            {
                System.IO.StreamReader scriptFile = new System.IO.StreamReader(uplScript.PostedFile.InputStream);
                txtScript.Text = scriptFile.ReadToEnd();
            }
        }

        protected void ddlConfig_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            if (ddlConfig.SelectedIndex != 0)
                LoadConfig(ddlConfig.SelectedValue.ToLowerInvariant());
        }

        #endregion

    }

}
